import json
import Interface
from Interface.litemall_po.utils.log_utils import logger


class BaseApi:
    def __init__(self, base_url):
        self.base_url = base_url
        admin_url = "admin/auth/login"
        admin_data = {"username": "admin123", "password": "admin123", "code": ""}
        admin_r = self.send("post", admin_url, json=admin_data)
        self.token = admin_r["data"]["token"]
        client_url = "wx/auth/login"
        client_data = {"username": "user123", "password": "user123"}
        client_r = self.send("post", client_url, json=client_data)
        self.client_token = client_r["data"]["token"]

    def send(self, method, url, **kwargs):
        # 问题1：接口里面直接使用requests
        # 解决方法：在base_api 中添加公共的send方法
        # 问题2：大量重复的base_url
        # 解决方案：在构造函数，实例化base_url，并且在send方法里拼接，无需重复编写self.base_url
        # 问题3：token 的获取也放到了构造函数里面
        # 解决方案：在构造函数，实例化base_url，并且在send方法里拼接，无需重复编写self.base_url
        r = Interface.request(method, self.base_url + url, **kwargs)
        logger.debug(f"{url}接口的响应为{json.dumps(r.json(), indent=2, ensure_ascii=False)}")
        return r.json()


